package com.ijmacd.footballtracker;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import org.apache.http.impl.cookie.DateUtils;

import com.ijmacd.footballtracker.Provider.Matches;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MatchListAdapter extends SimpleCursorAdapter {
	private static final int TYPE_HEADER = 0;
	private static final int TYPE_ITEM = 1;
	private static final int DEFAULT_SIZE = 20;
	private static final String TAG = "MatchListAdapter";
	Cursor mCursor;
	private int mLayout;
	int mColumnIndex;
	int mListSize = DEFAULT_SIZE;
	private ArrayAdapter<String> headers;
	private ArrayList<Integer> headers_pos;
	public boolean mDataValid;
	Handler h = new Handler();
	private MyDataSetObserver mDataSetObserver = new MyDataSetObserver();
	private MyContentObserver mContentObserver = new MyContentObserver(h);
	private Context mContext;
	private String[] mFrom;
	private int[] mTo;

	public MatchListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int categoryColumn) {
		super(context, layout, c, from, to);
		Log.d(TAG, "Created");
		mContext = context;
		mLayout = layout;
		mFrom = from;
		mTo = to;
		mCursor = c;
		mColumnIndex = categoryColumn;
		if(c != null){
			mDataValid = true;
			c.registerDataSetObserver(mDataSetObserver);
			c.registerContentObserver(mContentObserver);
		} else mDataValid = false;
		sortList();
	}

	private void sortList() {
		headers = new ArrayAdapter<String>(mContext, R.layout.list_header);
		headers_pos = new ArrayList<Integer>();
		int count = 0;
		mListSize = mCursor.getCount();
		if(mCursor.moveToFirst()){
			String lastdate = "";
			for(int i = 0; i < mListSize; i++){
				if(mCursor.moveToPosition(i)){
					String date = mCursor.getString(mColumnIndex);
					if(!date.equals(lastdate)){
						lastdate = date;
						try {
							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
							Date d = df.parse(date);
							date = DateUtils.formatDate(d, "EEEE, d MMMM");
						} catch (ParseException e) {
							Log.d(TAG, "Date parse failed: " + e.getMessage());
						}
						headers.add(date);
						headers_pos.add(i + count);
						count++;
					}
				}
			}
		}
	}

	@Override
	public int getCount() {
		return mListSize + headers.getCount(); // 1 for Loading
	}

	@Override
	public Object getItem(int position) {
		//Log.d(TAG, "Requested Item: " + position);
		int i = Collections.binarySearch(headers_pos, position);
		if(i >= 0){
			return headers.getItem(i);
		}
		if(position == getCount() - 1) return null;
		return super.getItem(position + i + 1);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
			//throw new IllegalStateException("this should only be called when the cursor is valid");
			//return headers.getView(0, convertView, parent);
			//TextView tv = new TextView(mContext);
			//tv.setText("WTF!?");
			//return tv;
			mCursor.requery();
		}
		//Log.d(TAG, "Requested View: " + position);
		int i = Collections.binarySearch(headers_pos, position);
		if(i >= 0){
			return headers.getView(i, convertView, parent);
		}
		//if(position == getCount() - 1){
		//	TextView tv = new TextView(mContext);
		//	tv.setText("Loading");
		//	mListSize += DEFAULT_SIZE;
		//	sortList();
		//	//LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, parent)
		//	return tv;
		//}
		//return super.getView(position + i + 1, convertView, parent);
		
		mCursor.moveToPosition(position + i + 1);
		int status = mCursor.getInt(MatchListActivity.COLUMN_INDEX_STATUS);
		View v = LayoutInflater.from(mContext).inflate(mLayout, null);
		String text;
		for(int j = 0; j < mFrom.length; j++){
			text = mCursor.getString(mCursor.getColumnIndex(mFrom[j]));
			if(status == Provider.STATUS_DUE){
				if(mFrom[j].equals(Matches.HOME_GOALS)) text = "";
				if(mFrom[j].equals(Matches.AWAY_GOALS)) text = "";
			}else if(status == Provider.STATUS_POSTPONED){
				if(mFrom[j].equals(Matches.HOME_GOALS)) text = "P";
				if(mFrom[j].equals(Matches.AWAY_GOALS)) text = "P";
			}
			((TextView)v.findViewById(mTo[j])).setText(text);
		}
		return v;
	}

	@Override
	public int getItemViewType(int position) {
		int i = Collections.binarySearch(headers_pos, position);
		if(i >= 0){
			return TYPE_HEADER;
		}
		return TYPE_ITEM;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

    public boolean areAllItemsSelectable() {  
        return false;  
    }  

    @Override  
    public boolean isEnabled(int position) {  
        return (getItemViewType(position) != TYPE_HEADER);  
    }  
    
    @Override  
    public long getItemId(int position) {  
        return position;  
    }

	public int getPosition(int position) {
		int i = Collections.binarySearch(headers_pos, position);
		if(i >= 0){
			return -i - 1;
		}
		return position + i + 1;
	}

	private class MyDataSetObserver extends DataSetObserver {
		@Override
		public void onChanged() {
			mDataValid = true;
			notifyDataSetChanged();
		}
		
		@Override
		public void onInvalidated() {
			mDataValid = false;
			notifyDataSetInvalidated();
		}
	}
	private class MyContentObserver extends ContentObserver {
		public MyContentObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			sortList();
			onContentChanged();
		}
	}
}
